<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/7/6
 * Time: 17:22
 */

namespace backend\models\c2\entity;


use common\models\c2\entity\WarehouseCommitNote;
use common\models\c2\entity\WarehouseCommitReceiptItem;
use common\models\c2\statics\WarehouseCommitNoteType;
use common\models\c2\statics\WarehouseCommitState;

class WarehouseCommitReceiptNote extends WarehouseCommitNote
{

    public function loadItems()
    {
        $this->items = $this->getCommitReceiptItems()->all();
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes); // TODO: Change the autogenerated stub
        if (!empty($this->items)) {
            foreach ($this->items as $item) {
                $attributes = [
                    'label' => isset($item['label']) ? $item['label'] : '',
                    'type' => WarehouseCommitNoteType::TYPE_RECEIPT,
                    'note_id' => $this->note_id,
                    'product_id' => isset($item['product_id']) ? $item['product_id'] : 0,
                    'number' => isset($item['number']) ? $item['number'] : 0,
                    'memo' => isset($item['memo']) ? $item['memo'] : '',
                    'position' => isset($item['position']) ? $item['position'] : 0,
                ];
                if (isset($item['id']) && $item['id'] == '') {
                    $itemModel = new WarehouseCommitReceiptItem();
                    $itemModel->setAttributes($attributes);
                    $itemModel->link('owner', $this);
                } elseif (isset($item['id'])) {
                    $itemModel = WarehouseCommitReceiptItem::findOne($item['id']);
                    if (!is_null($itemModel)) {
                        $itemModel->updateAttributes($attributes);
                    }
                }
            }
        }
    }

    public function setStateToCommit()
    {
        foreach ($this->getCommitReceiptItems()->all() as $item) {
            $product = $item->product;
            if (!is_null($product)) {
                $product->updateCounters(['stock' => $item->number]);
                $item->updateAttributes(['state' => WarehouseCommitState::COMMIT]);
            }
        }
        $this->updateAttributes(['state' => WarehouseCommitState::COMMIT]);
    }

}